package com.monitor.service.parser.impl;

import com.monitor.model.ServerStatus;
import com.monitor.service.parser.MetricParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 内存指标解析器
 * 负责解析内存使用情况
 */
public class MemoryMetricParser implements MetricParser {
    private static final Logger logger = LoggerFactory.getLogger(MemoryMetricParser.class);

    @Override
    public void parse(String commandOutput, ServerStatus status) {
        try {
            String[] lines = commandOutput.split("\\n");
            if (lines.length >= 2) {
                String memLine = lines[1]; // Mem: 行
                String[] parts = memLine.trim().split("\\s+");
                
                // 获取内存总量和已用量，单位MB
                if (parts.length >= 3) {
                    double total = Double.parseDouble(parts[1]);
                    double used = Double.parseDouble(parts[2]);
                    double percentage = Math.round((used / total) * 100.0);
                    
                    // 转换为GB并保留一位小数
                    double totalGB = Math.round(total / 1024.0 * 10) / 10.0;
                    double usedGB = Math.round(used / 1024.0 * 10) / 10.0;
                    
                    status.setMemoryInfo(String.format("已用%.1f GB / 总计%.1f GB (%.0f%%)", 
                        usedGB, totalGB, percentage));
                }
            }
        } catch (Exception e) {
            logger.error("解析内存信息失败: {}", e.getMessage());
            status.setMemoryInfo("解析错误");
        }
    }
} 